<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<style>
    div {
        color: red;
        color: #ff0000;
        color: rgba(255, 0, 0, .5);
        color: #ff000080;
    }
</style>

<body>

</body>
<script>

    // 16进制转rgba,-带透明度
    function hexToRgba(hex, opacity) {
        let result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
        return `rgba(${parseInt(result[1], 16)},${parseInt(
            result[2],
            16
        )},${parseInt(result[3], 16)},${opacity})`;
    }

    console.log(hexToRgba('#ffc2cc', .7))
    // or
    function HexToRGB(color, opacity) {
        let newColor = 'rgba(';

        //判断是三位还是六位
        if (color.length === 4) {
            let arry = [];

            for (let i = 1; i < color.length; i++) {
                arry.push(parseInt("0x" + color[i] + color[i]));
            }

            arry.forEach(function (item) {
                newColor += item + ', ';
            });
            newColor += opacity / 100 + ')';

            return newColor;
        } else {
            let arry = [];

            for (let i = 1; i < color.length; i += 2) {
                arry.push(parseInt("0x" + color.slice(i, i + 2)));
            }

            arry.forEach(function (item) {
                newColor += item + ', ';
            });
            newColor += opacity / 100 + ')';

            return newColor;
        }
    }

    console.log('....', HexToRGB('#ff0000', 77))

    // rgba-16
    function RGBToHex(rgba) {
        let str = rgba.slice(5, rgba.length - 1),
            arry = str.split(','),
            opa = Number(arry[3].trim()) * 100,
            strHex = "#",
            r = Number(arry[0].trim()),
            g = Number(arry[1].trim()),
            b = Number(arry[2].trim());

        strHex += ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);

        return { color: strHex, opacity: opa };
    }
    console.log(RGBToHex('rgba(255, 0, 0, .1)'))

</script>

</html>